package org.example.demo3.server.handler;

import org.example.demo3.common.exception.BaseException;
import org.example.demo3.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 捕获sql异常（主键相等）并抛出error
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLException ex){
        log.error("异常信息：{}",ex.getMessage());
        if(ex.getMessage().contains("Duplicate")){
            return Result.error("用户已存在");
        }
        else {
            return Result.error("未知错误");
        }
    }

}
